package com.ys.service.sys.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ys.dto.AddDto;
import com.ys.dto.DtreeSqlDto;
import com.ys.dto.EditDto;
import com.ys.dto.YsTreeDto;
import com.ys.entity.hr.ThrOperateCompanyApply;
import com.ys.entity.sys.TsOperateOrg;
import com.ys.mapper.sys.SysMapper;
import com.ys.mapper.sys.TsOperateOrgMapper;
import com.ys.service.sys.TsOperateOrgService;
import com.ys.vo.R;

@Service("tsOperateOrgService")
public class TsOperateOrgServiceImpl implements TsOperateOrgService {
	@Autowired
	private SysMapper sysMapper;
	@Autowired
	private TsOperateOrgMapper tsOperateOrgMapper;

	@Override
	@Transactional
	public R add(Long pid, String name) {
		
		if (pid == null) {
			return R.error("上级ID不能为空");
		}
		
		TsOperateOrg pEntity = new TsOperateOrg().setId(pid).queryFirst();
		if (pEntity == null) {
			return R.error("上级不存在");
		}
		if(pEntity.getStatus()==0){
			return R.error("上级已停用");
		}
		
		if (name == null || name.length() == 0) {
			return R.error("机构名称不能为空");
		}
		
		Long pNodeRgt = pEntity.getNodeRgt();
		sysMapper.updateTsOperateOrgNodeLftAddTwo(pNodeRgt);
		sysMapper.updateTsOperateOrgNodeRgtAddTwo(pNodeRgt);
		
		TsOperateOrg entity = null;
		{
			Long nodeLft = pEntity.getNodeRgt();
			Long nodeRgt = pEntity.getNodeRgt() + 1;
			Integer floor = pEntity.getFloor() + 1;
			String headUserId = null;
			
			entity = TsOperateOrg.tsOperateOrg(pid, name, nodeLft, nodeRgt, floor, headUserId, 1);
			tsOperateOrgMapper.insert(entity);
		}
		
		return R.ok(AddDto.closeAndReload());
	}

	@Override
	public R edit(Long id, String name, String headVgsbm, int status) {
		
		// 验证运营公司所属机构在范围内
		if (headVgsbm == null || headVgsbm.length() == 0) {
			return R.error("机构主管编码不能为空");
		}
		ThrOperateCompanyApply thrOperateCompanyApply = new ThrOperateCompanyApply().setVgsbm(headVgsbm).queryFirst();
		if (thrOperateCompanyApply == null) {
			return R.error("运营公司不存在");
		}
		Long operateOrgId = thrOperateCompanyApply.getOperateOrgId();
		if (operateOrgId == null) {
			return R.error("运营公司所属机构为空");
		} else if (operateOrgId.longValue() != id.longValue()) {
			return R.error("运营公司不在该机构下");
		}
		
		TsOperateOrg entity = new TsOperateOrg().setId(id).queryFirst();
		
		
		entity.setName(name)
			.setHeadVgsbm(headVgsbm)
			.setStatus(status);
		tsOperateOrgMapper.update(entity);
		
		return R.ok(EditDto.noAction());
	}

	@Override
	public DtreeSqlDto dtree() {
		
		DtreeSqlDto.StatusDto status = DtreeSqlDto.StatusDto.init(200, "");

		List<DtreeSqlDto.DataDto> data = new ArrayList<DtreeSqlDto.DataDto>();
		List<TsOperateOrg> listTsOperateOrg = new TsOperateOrg()
				.setOrderby("A.Id asc")
				.setStatus(1)
				.queryList();
		// 处理部门数据，方便遍历
		Map<Long, List<TsOperateOrg>> MAP_PID_LIST = new HashMap<Long, List<TsOperateOrg>>();
		for(TsOperateOrg tsOperateOrg : listTsOperateOrg) {
			List<TsOperateOrg> listValue = MAP_PID_LIST.containsKey(tsOperateOrg.getPid()) ? MAP_PID_LIST.get(tsOperateOrg.getPid()) : new ArrayList<TsOperateOrg>();
			listValue.add(tsOperateOrg);
			MAP_PID_LIST.put(tsOperateOrg.getPid(), listValue);
		}
		
		// 一级菜单
		{
			TsOperateOrg tsOperateOrgRoot = new TsOperateOrg().setPid(0L).queryFirst();
			String id = tsOperateOrgRoot.getId().toString();
			String title = tsOperateOrgRoot.getName();
			String parentId = tsOperateOrgRoot.getPid().toString();
			
			// 二级菜单
			List<DtreeSqlDto.DataDto> children = getChildren(tsOperateOrgRoot, MAP_PID_LIST);
			
			DtreeSqlDto.DataDto dataDto1 = new DtreeSqlDto.DataDto(id, title, parentId, DtreeSqlDto.DataDto.initCheckArr(null), children);
			data.add(dataDto1);
		}
		return new DtreeSqlDto(status, data);
	}
	
	private List<DtreeSqlDto.DataDto> getChildren(TsOperateOrg current, Map<Long, List<TsOperateOrg>> MAP_PID_LIST) {
		
		List<TsOperateOrg> listTsOperateOrg = MAP_PID_LIST.get(current.getId());
		List<DtreeSqlDto.DataDto> children = new ArrayList<DtreeSqlDto.DataDto>();
		if (listTsOperateOrg == null) {
			return null;
		} else {
			for(TsOperateOrg tsOperateOrg : listTsOperateOrg) {
				String id = tsOperateOrg.getId().toString();
				String title = tsOperateOrg.getName();
				String parentId = tsOperateOrg.getPid().toString();
				
				List<DtreeSqlDto.DataDto> childrenSub = getChildren(tsOperateOrg, MAP_PID_LIST);
				DtreeSqlDto.DataDto dataDtoSub = new DtreeSqlDto.DataDto(id, title, parentId, DtreeSqlDto.DataDto.initCheckArr(null), childrenSub);
				children.add(dataDtoSub);
			}
		}
		
		return children;
	}


	//根据id获取其底下所有的机构信息
	@Override
	public List<TsOperateOrg> getAllChildrenById(Long id) throws Exception {
		//获取所有运营机构信息
		List<TsOperateOrg> allList = new TsOperateOrg().setStatus(1).queryList();
		List<TsOperateOrg> childrenList = new ArrayList<>();
		for(TsOperateOrg orgItem:allList){
			boolean isChildern = isChildern(allList,id,orgItem.getId());
			if(isChildern){
				childrenList.add(orgItem);
			}
		}
		return childrenList;
	}

	//递归判断是否属于子信息
	public boolean isChildern(List<TsOperateOrg> allList,long pid,long id){
		boolean isChildern = false;
		List<TsOperateOrg> getInfoById = allList.stream().filter(item->item.getId()==id).collect(Collectors.toList());
		if(getInfoById.size()>0){
			TsOperateOrg infoById = getInfoById.get(0);
			if(infoById.getPid()!=null){
                if(infoById.getPid()==pid){
                    isChildern = true;
                }else {
                    isChildern = isChildern(allList,pid,infoById.getPid());
                }
            }

		}
		return isChildern;
	}

	@Override
	public YsTreeDto ysTree() {

		List<YsTreeDto.DataDto> data = new ArrayList<YsTreeDto.DataDto>();
		List<TsOperateOrg> listTsOperateOrg = new TsOperateOrg()
				.setOrderby("A.Id asc")
				.setStatus(1)
				.queryList();
		// 处理部门数据，方便遍历
		Map<Long, List<TsOperateOrg>> MAP_PID_LIST = new HashMap<Long, List<TsOperateOrg>>();
		for(TsOperateOrg tsOperateOrg : listTsOperateOrg) {
			List<TsOperateOrg> listValue = MAP_PID_LIST.containsKey(tsOperateOrg.getPid()) ? MAP_PID_LIST.get(tsOperateOrg.getPid()) : new ArrayList<TsOperateOrg>();
			listValue.add(tsOperateOrg);
			MAP_PID_LIST.put(tsOperateOrg.getPid(), listValue);
		}
		
		// 一级菜单
		{
			TsOperateOrg tsOperateOrgRoot = new TsOperateOrg().setPid(0L).queryFirst();
			String id = tsOperateOrgRoot.getId().toString();
			String title = tsOperateOrgRoot.getName();
			
			// 二级菜单
			List<YsTreeDto.DataDto> children = getYsTreeSub(tsOperateOrgRoot, MAP_PID_LIST);
			
			YsTreeDto.DataDto dataDto1 = new YsTreeDto.DataDto(id, title, children);
			data.add(dataDto1);
		}
		return new YsTreeDto(data);
	}
	
	private List<YsTreeDto.DataDto> getYsTreeSub(TsOperateOrg current, Map<Long, List<TsOperateOrg>> MAP_PID_LIST) {
		
		List<TsOperateOrg> listTsOperateOrg = MAP_PID_LIST.get(current.getId());
		List<YsTreeDto.DataDto> children = new ArrayList<YsTreeDto.DataDto>();
		if (listTsOperateOrg == null) {
			return null;
		} else {
			for(TsOperateOrg tsOperateOrg : listTsOperateOrg) {
				String id = tsOperateOrg.getId().toString();
				String title = tsOperateOrg.getName();
				
				List<YsTreeDto.DataDto> childrenSub = getYsTreeSub(tsOperateOrg, MAP_PID_LIST);
				YsTreeDto.DataDto dataDtoSub = new YsTreeDto.DataDto(id, title, childrenSub);
				children.add(dataDtoSub);
			}
		}
		
		return children;
	}

}
